import 'dart:async';

import 'package:app/constants/http_constants.dart';
import 'package:app/http/api_service.dart';
import 'package:app/models/response.dart';
import 'package:app/models/user.dart';
import 'package:app/router/index.dart';
import 'package:app/store/index.dart';
import 'package:app/widgets/message.dart';
import 'package:creato_ui/creato_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:otp_text_field/otp_text_field.dart';
import 'package:otp_text_field/style.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:provider/provider.dart';

// 功能枚举
enum VerificationCodePageActionType {
  phone,
  email,
}

class VerificationCodePage extends StatefulWidget {
  const VerificationCodePage(
      {super.key, required this.actionType, required this.account});

  final VerificationCodePageActionType actionType; // 功能类型
  final String account; // 账号(手机号或邮箱)

  @override
  State<VerificationCodePage> createState() => _VerificationCodePageState();
}

class _VerificationCodePageState extends State<VerificationCodePage> {
  late StreamController<ErrorAnimationType> _errorController;
  late TextEditingController _textcontroller;
  final timerNotifier = ValueNotifier<int>(60);

  @override
  void initState() {
    _errorController = StreamController<ErrorAnimationType>();
    _textcontroller = TextEditingController();
    print("account: ${widget.account} actionType: ${widget.actionType}");
    _sendVerificationCode();
    _countDown();
    super.initState();
  }

  // 标题
  Widget _buildTitle() {
    Widget _title;

    switch (widget.actionType) {
      case VerificationCodePageActionType.phone:
        _title = const Text("输入验证码");
        break;
      case VerificationCodePageActionType.email:
        _title = const Text("输入邮箱验证码");
        break;
    }

    return Align(
        alignment: Alignment.centerLeft,
        child: DefaultTextStyle(
            style: const TextStyle(
                fontSize: 24,
                color: Color(0xFF383838),
                fontWeight: FontWeight.w600),
            child: _title));
  }

  // 副标题
  Widget _buildSubTitle() {
    Widget _subTitle;

    switch (widget.actionType) {
      case VerificationCodePageActionType.phone:
        _subTitle = Text("验证码已发送至 ${widget.account}");
        break;
      case VerificationCodePageActionType.email:
        _subTitle = Text("验证码已发送至 ${widget.account},请查看邮件或者垃圾箱");
        break;
    }

    return Align(
        alignment: Alignment.centerLeft,
        child: DefaultTextStyle(
            style: const TextStyle(
              fontSize: 13,
              color: Color(0xFF999999),
            ),
            child: _subTitle));
  }

  // 发送验证码
  void _sendVerificationCode() async {
    switch (widget.actionType) {
      case VerificationCodePageActionType.phone:
        ResponseData data =
            await ApiService(context).getCaptcha(widget.account);
        break;
      case VerificationCodePageActionType.email:
        ResponseData data =
            await ApiService(context).sendEmailVcode(widget.account);
        break;
      default:
        print("unknown action type");
        break;
    }
    print("send verification code to ${widget.account}");
  }

  // 验证码输入完成执行的操作
  void _onCompleted(String value) async {
    // 验证验证码
    switch (widget.actionType) {
      case VerificationCodePageActionType.phone:
        ResponseData data = await ApiService(context)
            .updateUserInfo(UserInfo(phoneNum: widget.account, pvcode: value));
        if (data.code == HttpConstants.SUCCEED_CODE) {
          UserModel userModel = Provider.of<UserModel>(context, listen: false);
          userModel.phoneNum = widget.account;
          Message.showToast(msg: "换绑手机号成功");
          router.go("/home/user_info");
        } else {
          _errorController.add(ErrorAnimationType.shake);
          Future.delayed(const Duration(seconds: 1), () {
            _errorController.add(ErrorAnimationType.clear);
          });
        }
        break;
      case VerificationCodePageActionType.email:
        ResponseData data = await ApiService(context)
            .updateUserInfo(UserInfo(vcode: value, email: widget.account));
        if (data.code == HttpConstants.SUCCEED_CODE) {
          UserModel userModel = Provider.of<UserModel>(context, listen: false);
          userModel.email = widget.account;
          Message.showToast(msg: "换绑邮箱成功");
          router.go("/home/user_info");
        } else {
          _errorController.add(ErrorAnimationType.shake);
          Future.delayed(const Duration(seconds: 1), () {
            _errorController.add(ErrorAnimationType.clear);
          });
        }
        break;
      default:
        print("unknown action type");
        break;
    }
  }

  // 倒计时
  void _countDown() {
    if (timerNotifier.value > 0) {
      timerNotifier.value--;
      Future.delayed(const Duration(seconds: 1), _countDown);
    } else {
      timerNotifier.value = 60;
      _sendVerificationCode();
      _countDown();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 40, 20, 0),
          child: Column(
            children: [
              _buildTitle(),
              const SizedBox(height: 6.5),
              _buildSubTitle(),
              const SizedBox(height: 54),
              SizedBox(
                width: MediaQuery.of(context).size.width * 0.6,
                child: PinCodeTextField(
                  useExternalAutoFillGroup: true,
                  dialogConfig: DialogConfig(platform: PinCodePlatform.other),
                  controller: _textcontroller,
                  errorAnimationController: _errorController,
                  autoFocus: true,
                  separatorBuilder: (context, index) {
                    return const Spacer();
                  },
                  errorTextDirection: TextDirection.ltr,
                  useHapticFeedback: true,
                  pinTheme: PinTheme(
                      inactiveColor: Colors.black,
                      activeColor: Colors.black,
                      selectedColor: Colors.black,
                      errorBorderColor: Colors.red,
                      activeBorderWidth: 3,
                      inactiveBorderWidth: 3,
                      selectedBorderWidth: 3,
                      errorBorderWidth: 3,
                      fieldWidth: 23.5),
                  animationType: AnimationType.scale,
                  keyboardType: TextInputType.number,
                  appContext: context,
                  length: 4,
                  textStyle: const TextStyle(fontSize: 24, color: Colors.black),
                  onCompleted: (value) {
                    _onCompleted(value);
                  },
                  onChanged: (value) {
                    print("-----------------Changed: $value");
                  },
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              ValueListenableBuilder<int>(
                  valueListenable: timerNotifier,
                  builder: (context, count, child) {
                    return Text(
                      "$count s后重新发送",
                      style: const TextStyle(
                        fontSize: 13,
                        color: Color(0xFF999999),
                      ),
                    );
                  })
            ],
          ),
        ),
      ),
    );
  }
}
